<template>
  <div class="dicom-static-page">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <h2 class="page-title">静态DICOM加载</h2>
      </div>
      <div class="toolbar-right">
        <div class="connection-status">
          <span class="status-indicator" :class="{ 'connected': orthancConnected, 'disconnected': !orthancConnected }">
            {{ orthancConnected ? '🟢' : '🔴' }}
          </span>
          <span class="status-text">
            {{ orthancConnected ? 'Orthanc已连接' : 'Orthanc未连接' }}
          </span>
        </div>
        
        <div class="file-info" v-if="selectedFile">
          <span class="file-name">{{ selectedFile.name }}</span>
        </div>
        
        <div class="orthanc-controls">
          <select 
            v-model="selectedInstanceId" 
            class="instance-select"
            :disabled="!orthancConnected || loading"
            @click="onInstanceSelectClick"
          >
            <option value="">请选择DICOM实例</option>
            <optgroup v-for="study in availableStudies" :key="study.id" :label="study.label">
              <option 
                v-for="instance in study.instances" 
                :key="instance.id" 
                :value="instance.id"
              >
                {{ instance.label }}
              </option>
            </optgroup>
          </select>
          
          <button 
            class="refresh-btn" 
            @click="refreshInstanceList" 
            :disabled="!orthancConnected || loading"
            title="刷新实例列表"
          >
            🔄
          </button>
          
          <button 
            class="orthanc-btn" 
            @click="loadSelectedInstance()" 
            :disabled="!orthancConnected || loading || !selectedInstanceId"
          >
            加载选中实例
          </button>
        </div>
        
        <button class="select-file-btn" @click="triggerFileSelect">
          选择文件
        </button>
        <input 
          ref="fileInput" 
          type="file" 
          accept=".dcm,.dicom" 
          @change="onFileSelected" 
          style="display: none"
        />
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- DICOM查看器区域 -->
      <div class="viewer-container">
        <div v-if="!imageLoaded" class="empty-state">
          <div class="empty-content">
            <div class="empty-icon">📁</div>
            <div class="empty-title">
              {{ orthancConnected ? 'DICOM查看器已就绪' : '请选择DICOM文件' }}
            </div>
            <div class="empty-subtitle">
              {{ orthancConnected ? '点击刷新按钮或下拉框加载实例列表，或选择本地文件' : '支持 .dcm 和 .dicom 格式' }}
            </div>
            <div class="empty-actions">
              <button 
                v-if="orthancConnected && availableInstances.length > 0" 
                class="empty-btn primary" 
                @click="refreshInstanceList"
              >
                刷新实例列表
              </button>
              <button 
                v-if="orthancConnected" 
                class="empty-btn" 
                @click="loadDicomFromOrthanc()"
              >
                加载预设示例
              </button>
              <button class="empty-btn" @click="triggerFileSelect">
                选择本地文件
              </button>
            </div>
            
            <div v-if="orthancConnected && availableInstances.length > 0" class="instance-count">
              找到 {{ availableInstances.length }} 个DICOM实例
            </div>
          </div>
        </div>
        
        <div v-else class="dicom-viewer" ref="dicomContainer">
          <div v-if="loading" class="loading-overlay">
            <div class="loading-spinner"></div>
            <div class="loading-text">正在加载DICOM文件...</div>
          </div>
          
          <!-- 图像显示区域 -->
          <div class="image-display">
            <!-- 实际的DICOM图像 -->
            <div v-if="dicomImageUrl" class="dicom-image-container">
              <img 
                :src="dicomImageUrl" 
                alt="DICOM图像" 
                class="dicom-image"
                @load="console.log('DICOM图像加载完成')"
                @error="console.error('DICOM图像加载失败')"
              />
            </div>
            
            <!-- 占位符 -->
            <div v-else class="image-placeholder">
              <div class="display-message">
                {{ orthancConnected ? '点击"加载示例DICOM"或选择本地文件' : '请先连接Orthanc服务器' }}
              </div>
            </div>
          </div>
          
          <!-- 右侧信息面板 -->
          <div class="info-panel">
            <div class="info-title">DICOM信息</div>
            <div class="info-subtitle">
              {{ orthancConnected ? '从Orthanc或本地文件加载' : '支持 .dcm 和 .dicom 格式' }}
            </div>
            
            <!-- 基本文件信息 -->
            <div v-if="fileInfo" class="file-details">
              <h4 class="section-title">基本信息</h4>
              <div class="detail-item">
                <span class="detail-label">文件名:</span>
                <span class="detail-value">{{ fileInfo.fileName }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">文件大小:</span>
                <span class="detail-value">{{ formatFileSize(fileInfo.fileSize) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">图像尺寸:</span>
                <span class="detail-value">{{ fileInfo.dimensions }}</span>
              </div>
            </div>

            <!-- 患者信息 -->
            <div v-if="dicomMetadata" class="patient-info">
              <h4 class="section-title">患者信息</h4>
              <div class="detail-item">
                <span class="detail-label">姓名:</span>
                <span class="detail-value patient-name">{{ dicomMetadata.patientName || 'N/A' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">患者ID:</span>
                <span class="detail-value">{{ dicomMetadata.patientID || 'N/A' }}</span>
              </div>
              <div v-if="dicomMetadata.patientSex" class="detail-item">
                <span class="detail-label">性别:</span>
                <span class="detail-value">{{ formatPatientSex(dicomMetadata.patientSex) }}</span>
              </div>
              <div v-if="dicomMetadata.patientAge" class="detail-item">
                <span class="detail-label">年龄:</span>
                <span class="detail-value">{{ dicomMetadata.patientAge }}</span>
              </div>
              <div v-if="dicomMetadata.patientBirthDate" class="detail-item">
                <span class="detail-label">出生日期:</span>
                <span class="detail-value">{{ formatDate(dicomMetadata.patientBirthDate) }}</span>
              </div>
            </div>
            
            <!-- 研究信息 -->
            <div v-if="dicomMetadata" class="study-info">
              <h4 class="section-title">研究信息</h4>
              <div v-if="dicomMetadata.studyDescription" class="detail-item">
                <span class="detail-label">研究描述:</span>
                <span class="detail-value">{{ dicomMetadata.studyDescription }}</span>
              </div>
              <div v-if="dicomMetadata.seriesDescription" class="detail-item">
                <span class="detail-label">系列描述:</span>
                <span class="detail-value">{{ dicomMetadata.seriesDescription }}</span>
              </div>
              <div v-if="dicomMetadata.modality" class="detail-item">
                <span class="detail-label">模态:</span>
                <span class="detail-value">{{ dicomMetadata.modality }}</span>
              </div>
              <div v-if="dicomMetadata.studyDate" class="detail-item">
                <span class="detail-label">研究日期:</span>
                <span class="detail-value">{{ formatDate(dicomMetadata.studyDate) }}</span>
              </div>
              <div v-if="dicomMetadata.studyTime" class="detail-item">
                <span class="detail-label">研究时间:</span>
                <span class="detail-value">{{ formatTime(dicomMetadata.studyTime) }}</span>
              </div>
              <div v-if="dicomMetadata.institutionName" class="detail-item">
                <span class="detail-label">医疗机构:</span>
                <span class="detail-value">{{ dicomMetadata.institutionName }}</span>
              </div>
            </div>

            <!-- 图像参数 -->
            <div v-if="dicomMetadata" class="image-params">
              <h4 class="section-title">图像参数</h4>
              <div v-if="dicomMetadata.imageWidth && dicomMetadata.imageHeight" class="detail-item">
                <span class="detail-label">图像尺寸:</span>
                <span class="detail-value">{{ dicomMetadata.imageWidth }} × {{ dicomMetadata.imageHeight }}</span>
              </div>
              <div v-if="dicomMetadata.pixelSpacing" class="detail-item">
                <span class="detail-label">像素间距:</span>
                <span class="detail-value">{{ dicomMetadata.pixelSpacing }}</span>
              </div>
              <div v-if="dicomMetadata.sliceThickness" class="detail-item">
                <span class="detail-label">层厚:</span>
                <span class="detail-value">{{ dicomMetadata.sliceThickness }} mm</span>
              </div>
              <div v-if="dicomMetadata.numberOfFrames" class="detail-item">
                <span class="detail-label">帧数:</span>
                <span class="detail-value">{{ dicomMetadata.numberOfFrames }}</span>
              </div>
              <div v-if="dicomMetadata.manufacturerModelName" class="detail-item">
                <span class="detail-label">设备型号:</span>
                <span class="detail-value">{{ dicomMetadata.manufacturerModelName }}</span>
              </div>
            </div>

            <!-- 技术信息 -->
            <div v-if="dicomMetadata" class="technical-info">
              <h4 class="section-title">技术信息</h4>
              <div class="detail-item">
                <span class="detail-label">研究UID:</span>
                <span class="detail-value uid-value" :title="dicomMetadata.studyInstanceUID">
                  {{ dicomMetadata.studyInstanceUID.slice(-12) }}...
                </span>
              </div>
              <div class="detail-item">
                <span class="detail-label">系列UID:</span>
                <span class="detail-value uid-value" :title="dicomMetadata.seriesInstanceUID">
                  {{ dicomMetadata.seriesInstanceUID.slice(-12) }}...
                </span>
              </div>
              <div class="detail-item">
                <span class="detail-label">实例UID:</span>
                <span class="detail-value uid-value" :title="dicomMetadata.sopInstanceUID">
                  {{ dicomMetadata.sopInstanceUID.slice(-12) }}...
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { orthancService, type DicomInstanceMetadata } from '@/services/orthanc.service'
import { exampleDicomInstance, type DicomInstancePath } from '@/config/orthanc.config'
import { testOrthancIntegration } from '@/utils/orthanc-test'

// 响应式数据
const selectedFile = ref<File | null>(null)
const loading = ref(false)
const imageLoaded = ref(false)
const dicomContainer = ref<HTMLElement | null>(null)
const fileInput = ref<HTMLInputElement | null>(null)
const orthancConnected = ref(false)
const dicomImageUrl = ref<string | null>(null)

// Orthanc实例选择
const selectedInstanceId = ref('')
const availableStudies = ref<any[]>([])
const availableInstances = ref<any[]>([])
const loadingInstances = ref(false)

// 文件信息
const fileInfo = ref<{
  fileName: string
  fileSize: number
  dimensions: string
  patientId?: string
} | null>(null)

// DICOM元数据
const dicomMetadata = ref<DicomInstanceMetadata | null>(null)

// 触发文件选择
const triggerFileSelect = () => {
  fileInput.value?.click()
}

// 文件选择处理
const onFileSelected = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return
  
  selectedFile.value = file
  loading.value = true
  
  try {
    await loadDicomFile(file)
  } catch (error) {
    console.error('加载DICOM文件失败:', error)
    alert('加载DICOM文件失败，请检查文件格式是否正确')
  } finally {
    loading.value = false
  }
}

// 加载DICOM文件的核心逻辑
const loadDicomFile = async (file: File) => {
  // 这里应该集成Cornerstone.js来加载和显示DICOM文件
  // 目前先模拟加载过程
  
  fileInfo.value = {
    fileName: file.name,
    fileSize: file.size,
    dimensions: '512 x 512',
    patientId: 'DEMO001'
  }
  
  // 模拟加载延迟
  await new Promise(resolve => setTimeout(resolve, 1500))
  
  imageLoaded.value = true
}

// 从Orthanc加载DICOM图像
const loadDicomFromOrthanc = async (instancePath?: DicomInstancePath) => {
  loading.value = true
  
  try {
    // 使用示例实例路径或传入的路径
    const path = instancePath || exampleDicomInstance
    
    console.log('正在从Orthanc加载DICOM图像...', path)
    
    // 首先验证实例是否存在
    const instanceExists = await orthancService.verifyInstanceExists(path)
    if (!instanceExists) {
      throw new Error('DICOM实例不存在，请检查UID是否正确或选择其他实例')
    }
    
    // 并行获取图像和元数据
    const [imageBlob, metadata] = await Promise.all([
      orthancService.getDicomImage(path),
      orthancService.getDicomMetadata(path)
    ])
    
    // 创建图像URL
    const imageUrl = URL.createObjectURL(imageBlob)
    dicomImageUrl.value = imageUrl
    dicomMetadata.value = metadata
    
    // 更新文件信息
    fileInfo.value = {
      fileName: metadata.patientName 
        ? `${metadata.patientName} - DICOM实例`
        : `DICOM实例 (${path.sopInstanceUID.slice(-8)})`,
      fileSize: imageBlob.size,
      dimensions: metadata.imageWidth && metadata.imageHeight 
        ? `${metadata.imageWidth} x ${metadata.imageHeight}` 
        : '未知',
      patientId: metadata.patientID || metadata.patientName || 'N/A'
    }
    
    imageLoaded.value = true
    console.log('DICOM图像加载成功', metadata)
    
  } catch (error) {
    console.error('从Orthanc加载DICOM失败:', error)
    alert(`从Orthanc加载DICOM失败: ${error}`)
  } finally {
    loading.value = false
  }
}

// 测试Orthanc连接
const testOrthancConnection = async () => {
  try {
    const connected = await orthancService.testConnection()
    orthancConnected.value = connected
    
    if (connected) {
      console.log('Orthanc连接成功')
      // 连接成功，但不自动刷新实例列表，等用户主动触发
      console.log('💡 提示：点击刷新按钮或选择实例下拉框来加载DICOM实例列表')
    } else {
      console.warn('Orthanc连接失败')
    }
    
    return connected
  } catch (error) {
    console.error('测试Orthanc连接时出错:', error)
    orthancConnected.value = false
    return false
  }
}

// 刷新实例列表
const refreshInstanceList = async () => {
  if (!orthancConnected.value) return
  
  loadingInstances.value = true
  
  try {
    console.log('🔄 刷新Orthanc实例列表...')
    console.time('⏱️ 实例列表加载耗时')
    
    // 获取所有研究
    const studies = await orthancService.getStudies()
    console.log(`找到 ${studies.length} 个研究`)
    
    // 并发处理所有研究
    const studyPromises = studies.map(async (study) => {
      const patientName = study.PatientMainDicomTags?.PatientName || 'Unknown Patient'
      const studyDescription = study.MainDicomTags?.StudyDescription || 'No Description'
      const studyDate = study.MainDicomTags?.StudyDate || ''
      
      const studyLabel = `${patientName} - ${studyDescription} (${formatDate(studyDate)})`
      
      // 并发获取研究中的所有系列
      const seriesPromises = (study.Series || []).map(async (seriesId: string) => {
        try {
          const seriesResponse = await fetch(`/api/orthanc/series/${seriesId}`)
          const seriesData = await seriesResponse.json()
          
          const seriesDescription = seriesData.MainDicomTags?.SeriesDescription || 'No Description'
          const modality = seriesData.MainDicomTags?.Modality || 'Unknown'
          
          // 只获取系列中实例的基本信息，不预加载详细数据
          const instanceCount = seriesData.Instances?.length || 0
          
          const seriesInstances = []
          for (let i = 0; i < instanceCount; i++) {
            const instanceId = seriesData.Instances[i]
            
            const instanceLabel = `${seriesDescription} - ${modality} - 实例 ${i + 1}`
            
            const instance = {
              id: instanceId,
              label: instanceLabel,
              // 延迟加载的字段，只在需要时获取
              sopInstanceUID: null,
              studyInstanceUID: study.MainDicomTags?.StudyInstanceUID,
              seriesInstanceUID: seriesData.MainDicomTags?.SeriesInstanceUID,
              patientName,
              studyDescription,
              seriesDescription,
              modality,
              instanceNumber: i + 1,
              // 标记为未加载详细信息
              detailsLoaded: false
            }
            
            seriesInstances.push(instance)
          }
          
          return seriesInstances
        } catch (error) {
          console.warn(`获取系列失败: ${seriesId}`)
          return []
        }
      })
      
      // 等待所有系列加载完成
      const allSeriesInstances = await Promise.all(seriesPromises)
      const studyInstances = allSeriesInstances.flat()
      
      return {
        studyData: {
          id: study.ID,
          label: studyLabel,
          instances: studyInstances
        },
        instances: studyInstances
      }
    })
    
    // 等待所有研究加载完成
    const allStudiesResults = await Promise.all(studyPromises)
    
    // 提取结果
    const studyList = []
    const instanceList = []
    
    for (const result of allStudiesResults) {
      if (result.instances.length > 0) {
        studyList.push(result.studyData)
        instanceList.push(...result.instances)
      }
    }
    
    availableStudies.value = studyList
    availableInstances.value = instanceList
    
    console.timeEnd('⏱️ 实例列表加载耗时')
    console.log(`✅ 并发加载了 ${instanceList.length} 个DICOM实例的基本信息`)
    
  } catch (error) {
    console.error('刷新实例列表失败:', error)
    availableStudies.value = []
    availableInstances.value = []
  } finally {
    loadingInstances.value = false
  }
}

// 处理实例选择下拉框点击事件
const onInstanceSelectClick = async () => {
  // 如果还没有加载实例列表，则自动刷新
  if (orthancConnected.value && availableInstances.value.length === 0 && !loadingInstances.value) {
    console.log('🔄 首次点击下拉框，自动刷新实例列表...')
    await refreshInstanceList()
  }
}

// 按需获取实例详细信息
const loadInstanceDetails = async (instanceId: string) => {
  try {
    const instanceResponse = await fetch(`/api/orthanc/instances/${instanceId}`)
    const instanceData = await instanceResponse.json()
    
    return {
      instanceNumber: instanceData.MainDicomTags?.InstanceNumber || '1',
      sopInstanceUID: instanceData.MainDicomTags?.SOPInstanceUID || instanceId
    }
  } catch (error) {
    console.warn(`获取实例详细信息失败: ${instanceId}`)
    return {
      instanceNumber: '1',
      sopInstanceUID: instanceId
    }
  }
}

// 加载选中的实例
const loadSelectedInstance = async () => {
  if (!selectedInstanceId.value) {
    alert('请先选择一个DICOM实例')
    return
  }
  
  loading.value = true
  
  try {
    console.time('⏱️ 实例加载耗时')
    
    // 找到选中的实例信息
    const selectedInstance = availableInstances.value.find(
      instance => instance.id === selectedInstanceId.value
    )
    
    if (!selectedInstance) {
      throw new Error('未找到选中的实例')
    }
    
    console.log('🚀 正在加载选中的DICOM实例...', selectedInstance)
    
    // 并发：同时加载图像和详细信息
    const loadPromises: Promise<any>[] = [
      orthancService.getDicomImageByInstanceId(selectedInstanceId.value)
    ]
    
    // 如果实例详细信息未加载，并发获取
    let detailsPromise: Promise<any> | null = null
    if (!selectedInstance.detailsLoaded) {
      console.log('📥 并发获取实例详细信息...')
      detailsPromise = loadInstanceDetails(selectedInstance.id)
      loadPromises.push(detailsPromise)
    }
    
    // 等待所有并发请求完成
    const results = await Promise.all(loadPromises)
    const imageBlob = results[0]
    
    // 如果获取了详细信息，更新实例
    if (detailsPromise) {
      const details = results[1]
      selectedInstance.sopInstanceUID = details.sopInstanceUID
      selectedInstance.instanceNumber = details.instanceNumber
      selectedInstance.detailsLoaded = true
    }
    
    // 构建DicomInstancePath用于获取元数据
    const instancePath: DicomInstancePath = {
      studyInstanceUID: selectedInstance.studyInstanceUID,
      seriesInstanceUID: selectedInstance.seriesInstanceUID,
      sopInstanceUID: selectedInstance.sopInstanceUID!,
      frameNumber: 1
    }
    
    // 获取元数据
    const metadata = await orthancService.getDicomMetadata(instancePath)
    
    console.timeEnd('⏱️ 实例加载耗时')
    
    // 创建图像URL
    const imageUrl = URL.createObjectURL(imageBlob)
    dicomImageUrl.value = imageUrl
    dicomMetadata.value = metadata
    
    // 更新文件信息
    fileInfo.value = {
      fileName: selectedInstance.patientName 
        ? `${selectedInstance.patientName} - ${selectedInstance.seriesDescription}`
        : `DICOM实例 (${selectedInstance.instanceNumber})`,
      fileSize: imageBlob.size,
      dimensions: metadata.imageWidth && metadata.imageHeight 
        ? `${metadata.imageWidth} x ${metadata.imageHeight}` 
        : '未知',
      patientId: metadata.patientID || metadata.patientName || 'N/A'
    }
    
    imageLoaded.value = true
    console.log('选中的DICOM实例加载成功', {
      instance: selectedInstance,
      metadata
    })
    
  } catch (error) {
    console.error('加载选中实例失败:', error)
    alert(`加载选中实例失败: ${error}`)
  } finally {
    loading.value = false
  }
}

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化DICOM日期
const formatDate = (dateStr: string): string => {
  if (!dateStr) return 'N/A'
  
  // DICOM日期格式: YYYYMMDD
  if (dateStr.length === 8) {
    const year = dateStr.substring(0, 4)
    const month = dateStr.substring(4, 6)
    const day = dateStr.substring(6, 8)
    return `${year}-${month}-${day}`
  }
  
  return dateStr
}

// 格式化DICOM时间
const formatTime = (timeStr: string): string => {
  if (!timeStr) return 'N/A'
  
  // DICOM时间格式: HHMMSS.FFFFFF
  if (timeStr.length >= 6) {
    const hours = timeStr.substring(0, 2)
    const minutes = timeStr.substring(2, 4)
    const seconds = timeStr.substring(4, 6)
    return `${hours}:${minutes}:${seconds}`
  }
  
  return timeStr
}

// 格式化患者性别
const formatPatientSex = (sex: string): string => {
  switch (sex?.toUpperCase()) {
    case 'M':
      return '男'
    case 'F':
      return '女'
    case 'O':
      return '其他'
    default:
      return sex || 'N/A'
  }
}

onMounted(async () => {
  // 初始化DICOM查看器
  console.log('初始化DICOM查看器')
  
  // 测试Orthanc连接
  await testOrthancConnection()
  
  // 在开发模式下运行完整的集成测试
  if (import.meta.env.DEV) {
    console.log('🔧 开发模式：运行 Orthanc 集成测试')
    setTimeout(async () => {
      await testOrthancIntegration()
    }, 1000)
  }
})

onUnmounted(() => {
  // 清理资源
  console.log('清理DICOM查看器资源')
  
  // 清理图像URL
  if (dicomImageUrl.value) {
    URL.revokeObjectURL(dicomImageUrl.value)
  }
})
</script>

<style scoped>
.dicom-static-page {
  height: 100%;
  width: 100%;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
}

/* 顶部工具栏 */
.toolbar {
  height: 60px;
  background: white;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  flex-shrink: 0;
}

.toolbar-left {
  display: flex;
  align-items: center;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.status-indicator {
  font-size: 12px;
}

.status-text {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.connection-status .status-text {
  color: #666;
}

.connection-status.connected .status-text {
  color: #28a745;
}

.orthanc-btn {
  background: #28a745;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.orthanc-btn:hover:not(:disabled) {
  background: #218838;
}

.orthanc-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.orthanc-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.instance-select {
  min-width: 300px;
  max-width: 400px;
  padding: 8px 12px;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  font-size: 14px;
  background: white;
  cursor: pointer;
}

.instance-select:disabled {
  background: #f8f9fa;
  color: #6c757d;
  cursor: not-allowed;
}

.instance-select optgroup {
  font-weight: bold;
  color: #333;
  background: #f8f9fa;
}

.instance-select option {
  font-weight: normal;
  color: #666;
  padding: 4px 8px;
}

.refresh-btn {
  background: #17a2b8;
  color: white;
  border: none;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
  min-width: 40px;
}

.refresh-btn:hover:not(:disabled) {
  background: #138496;
}

.refresh-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.file-info {
  display: flex;
  align-items: center;
  color: #666;
}

.file-name {
  font-size: 14px;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.select-file-btn {
  background: #007bff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.select-file-btn:hover {
  background: #0056b3;
}

/* 主内容区 */
.main-content {
  flex: 1;
  padding: 0;
  overflow: hidden;
}

.viewer-container {
  height: 100%;
  width: 100%;
  position: relative;
}

/* 空状态 */
.empty-state {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
}

.empty-content {
  text-align: center;
  padding: 40px;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.empty-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.empty-subtitle {
  font-size: 14px;
  color: #666;
  margin-bottom: 24px;
}

.empty-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  flex-wrap: wrap;
}

.empty-btn {
  background: #6c757d;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.empty-btn:hover {
  background: #5a6268;
}

.empty-btn.primary {
  background: #007bff;
}

.empty-btn.primary:hover {
  background: #0056b3;
}

.instance-count {
  margin-top: 16px;
  padding: 8px 16px;
  background: #e3f2fd;
  border: 1px solid #2196f3;
  border-radius: 6px;
  color: #1976d2;
  font-size: 14px;
  font-weight: 500;
  text-align: center;
}

/* DICOM查看器 */
.dicom-viewer {
  height: 100%;
  display: flex;
  background: white;
  position: relative;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 14px;
  color: #666;
}

/* 图像显示区域 */
.image-display {
  flex: 1;
  background: #f8f9fa;
  border: 2px dashed #dee2e6;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 16px;
  border-radius: 8px;
}

.image-placeholder {
  text-align: center;
  color: #6c757d;
}

.display-message {
  font-size: 16px;
  color: #6c757d;
}

/* DICOM图像容器 */
.dicom-image-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #000;
}

.dicom-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  border-radius: 4px;
}

/* 右侧信息面板 */
.info-panel {
  width: 300px;
  background: white;
  border-left: 1px solid #e9ecef;
  padding: 24px;
  flex-shrink: 0;
}

.info-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.info-subtitle {
  font-size: 14px;
  color: #6c757d;
  margin-bottom: 24px;
}

.file-details {
  border-top: 1px solid #e9ecef;
  padding-top: 16px;
}

.patient-info {
  margin-top: 24px;
  border-top: 1px solid #e9ecef;
  padding-top: 16px;
}

.study-info {
  margin-top: 24px;
  border-top: 1px solid #e9ecef;
  padding-top: 16px;
}

.image-params {
  margin-top: 24px;
  border-top: 1px solid #e9ecef;
  padding-top: 16px;
}

.technical-info {
  margin-top: 24px;
  border-top: 1px solid #e9ecef;
  padding-top: 16px;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin: 0 0 12px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #f8f9fa;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f8f9fa;
}

.detail-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.detail-value {
  font-size: 14px;
  color: #333;
  text-align: right;
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.patient-name {
  font-weight: 600;
  color: #007bff !important;
  max-width: 180px !important;
}

.uid-value {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #666;
  cursor: pointer;
}

.uid-value:hover {
  color: #007bff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar {
    padding: 0 16px;
  }
  
  .page-title {
    font-size: 16px;
  }
  
  .dicom-viewer {
    flex-direction: column;
  }
  
  .info-panel {
    width: 100%;
    border-left: none;
    border-top: 1px solid #e9ecef;
  }
  
  .toolbar-right {
    gap: 8px;
  }
  
  .file-name {
    max-width: 120px;
  }
  
  .orthanc-controls {
    flex-direction: column;
    gap: 8px;
    align-items: stretch;
  }
  
  .instance-select {
    min-width: auto;
    max-width: none;
  }
}
</style>

